//定义一个变量用于接受数据
var selectLearnType;

//用于接受修改学习的问题ID
var questionId

//用于接受修改学习的问题内容
var questionValue

//用于存储选择类型的值
var selectLearnTypeValue;

layui.use(['form', 'layer', 'laydate', 'table', 'laytpl', 'element'], function () {
    var element = layui.element;
    var laydate = layui.laydate;

    //日期
    function getNowFormatDate() {
        var date = new Date();
        var month = date.getMonth() + 1;
        var strDate = date.getDate();
        var hours = date.getHours();
        var minutes = date.getMinutes();
        var seconds = date.getSeconds();
        if (month >= 1 && month <= 9) {
            month = "0" + month;
        }
        if (strDate >= 0 && strDate <= 9) {
            strDate = "0" + strDate;
        }
        if (hours >= 0 && hours <= 9) {
            hours = "0" + hours;
        }
        if (minutes >= 0 && minutes <= 9) {
            minutes = "0" + minutes;
        }
        if (seconds >= 0 && seconds <= 9) {
            seconds = "0" + seconds;
        }
        var currentdate = "'" + date.getFullYear() + "-" + month + "-" + strDate
            + " " + hours + ":" + minutes + ":" + seconds + "'";
        return currentdate;
    }

    var getNowFormatDate = getNowFormatDate();
    var dateMin = laydate.render({
        elem: '#regDateMin',
        type: 'datetime',
        min: "1970-01-01",//设置min默认最小值
        max: getNowFormatDate,//设置一个默认最大值
        done: function (value, dates) {
            dateMax.config.min = {
                year: dates.year,
                month: dates.month - 1, //关键
                date: dates.date,
                hours: 0,
                minutes: 0,
                seconds: 0
            };
        }
    });
    var dateMax = laydate.render({
        elem: '#regDateMax',
        type: 'datetime',
        min: "1970-01-01",//设置min默认最小值
        max: getNowFormatDate,
        done: function (value, dates) {
            dateMin.config.max = {
                year: dates.year,
                month: dates.month - 1,//关键
                date: dates.date,
                hours: 0,
                minutes: 0,
                seconds: 0
            }
        }
    });
    var form = layui.form,
        layer = layui.layer;
    $ = layui.jquery,
        laytpl = layui.laytpl,
        table = layui.table;

    var tableIns = table.render({
        elem: '#learningAnalysisList',
        //url : '../json/learningAnalysisList.json',
        url: 'queryAllNeedStudyQuestionBase',
        cellMinWidth: 95,
        page: true,
        limit: 10,
        limits: [10, 20, 30, 40, 50],
        id: "newsListTable",
        where:{packageId:packageId},
        cols: [[
            /*{type: "checkbox", fixed:"left", width:50 },*/
            {field: 'question', title: '待学习问题', width: 350},
            {
                field: 'status', title: '状态', align: 'center', templet: function (d) {

                if (d.status != null) {

                    if (d.status == "NOT_LEARN") {

                        return "待学习"
                    }

                    return "已学习";
                }

                return "未知状态";
            }
            },
            {field: 'sourceCallHistoryId', title: '来源', align: 'center',templet:function (d) {



                return d.questionSourceType==null?"未知":d.questionSourceType=="CALL_RECORDS"?"通话记录":"小程序训练";
            }
            },
            {field: 'modTime', title: '更新时间', align: 'center', minWidth: 200},
            {title: '操作', width: 170, templet: '#learningAnalysisBar', fixed: "right", align: "center"}
        ]]
    });


    //搜索【此功能需要后台配合，所以暂时没有动态效果演示】
    $(".search_btn").on("click", function () {

        table.reload("newsListTable", {
            page: {
                curr: 1 //重新从第 1 页开始
            },
            where: {
                question: $("#question").val() ,
                status:$("#questionStatus").val(),
                packageId:packageId
                //搜索的关键字
            }
        })

       /* if ($(".searchVal").val() != ''||$) {
            table.reload("newsListTable", {
                page: {
                    curr: 1 //重新从第 1 页开始
                },
                where: {
                    key: $(".searchVal").val()  //搜索的关键字
                }
            })
        } else {
            layer.msg("请输入搜索的内容");
        }*/

    });


    //弹出选择添加或者编辑问题窗口
    function addLearningAnalysis(edit) {
        selectLearnType = layer.open({
            type: 1,
            title: '选择添加类型',
            area: ['60%', '100px'],
            closeBtn: 1,
            //btn: "取消",
            //btn:['取消','保存'],
            content: $("#selectLearnType")//这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
        });

    }

    /*//弹出添加或编辑问题的窗口
    function addLearningAnalysis(edit){


    }*/
    /*
        $("#add_btn").click(function () {
            addLearningAnalysis(false);
        });
    */


    //监听选择添加类型的select下拉框
    form.on('select(selectLearn)', function (data) {

        var selectValue = data.value; //得到被选中的值

        if (selectValue != '') {

            selectLearnTypeValue = selectValue;

            var addKnowledgeBaseWin = window.parent.layer.open({
                id: "knowledgeBase",
                type: 2,
                title: '添加问题',
                area: ['70%', '75%'],
                closeBtn: "1",
                btn: ['保存', '取消'],
                content: baseUrl+ "/learningAnalysis/addLearningAnalysis",//这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                yes: function (index, layero) {

                    //获取iframe层的提交按钮对象
                    var submitButton = window.parent.layer.getChildFrame('button', index);

                    //我点!
                    submitButton.click();

                    $(".search_btn").click();//触发reload操作
                }
                , btn2: function (index) {

                    window.parent.layer.msg("取消学习");
                    window.parent.layer.close(index);

                }
            });
            window.parent.layer.close(selectLearnType);
            setTimeout(function(){
                window.parent.layer.tips('点击关闭，返回上个页面', '.layui-layer-setwin .layui-layer-close', {
                    tips: 3
                });
            },500);
            window.parent.layer.full(addKnowledgeBaseWin);
        }


    });

    //监听工具条
    table.on('tool(learningAnalysisList)', function (obj) { //注：tool是工具条事件名，test是table原始容器的属性 lay-filter="对应的值"
        var data = obj.data; //获得当前行数据
        var layEvent = obj.event; //获得 lay-event 对应的值（也可以是表头的 event 参数对应的值）
        //ar tr = obj.tr; //获得当前行 tr 的DOM对象

        //弹出选框
        if (layEvent == "edit") {

            questionId = data.id
            questionValue=data.question;

            var editKnowledgeBaseWin = window.parent.layer.open({
                id: "knowledgeBase",
                type: 2,
                title: '添加问题',
                area: ['70%', '75%'],
                closeBtn: "1",
                btn: ['保存', '取消'],
                content: baseUrl+ "/learningAnalysis/addLearningAnalysis",//这里content是一个DOM，注意：最好该元素要存放在body最外层，否则可能被其它的相对元素所影响
                yes: function (index, layero) {

                    //获取iframe层的提交按钮对象
                    var submitButton = window.parent.layer.getChildFrame('button', index);

                    //我点!
                    submitButton.click();

                }
                , btn2: function (index) {

                    window.parent.layer.msg("取消学习");
                    window.parent.layer.close(index);

                },
            });
            setTimeout(function(){
                window.parent.layer.tips('点击关闭，返回上个页面', '.layui-layer-setwin .layui-layer-close', {
                    tips: 3
                });
            },500);
            window.parent.layer.full(editKnowledgeBaseWin);

            //addLearningAnalysis(false);
        } else if (layEvent == "delete") {


            layer.confirm('确认删除吗?', {icon: 3, title: '提示'}, function (index) {


                //弹出loading层,友好提示
                var loading = layer.load(1, {
                    shade: [0.1,'#fff'] //0.1透明度的白色背景
                });
                //do something

                $.ajax({
                    type: "get",
                    data: {'id': data.id},
                    dataType: "json",
                    url: "deleteById",
                    success: function (callBackData) {

                        layer.close(loading);

                        if (callBackData.code == '1') {

                            obj.del();

                        }
                        layer.msg(callBackData.msg);

                    },
                    error: function (callBackData) {

                        layer.close(loading);

                        layer.msg("目前访问人数过多,请稍后再试")
                    }
                })
                layer.close(index);
            });

            //发送阿贾克斯请求


        }

    });


    //搜索标题框按回车进行搜索
    $(document).on({

        keydown:function (event) {
            if(event.keyCode==13){
                $("#search").click();
            }
        }

    },'#question')

    //监听选择框按回车进行搜索
    form.on("select(questionStatus)",function (data) {

        $("#search").click();
        //更新渲染
        form.render('select')
    })

});